var hccmConfig = require('@/common/hccm-config.js');
//验证邮箱格式
function checkEmail(email) {
	return RegExp(/^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/).test(
		email);
}
//校验手机格式
function checkMobile(mobile) {
	return RegExp(/^1\d{10}$/).test(mobile);
}
//校验身份证号码
function checkIDCard(idCard) {
	const userCardreg = /^([1-6][1-9]|50)\d{4}(18|19|20)\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
	const taiwanreg = /^[A-Z][0-9]{9}$/
	const xianggangreg = /^((\s?[A-Za-z])|([A-Za-z]{2}))\d{6}(([0−9aA])|([0-9aA]))$/
	const aomenreg = /^[157][0-9]{6}\([0-9]\)$/
	const taibao = /^[0-9]{8}$/
	const huzhao1 = /^[a-zA-Z]{5,17}$/
	const huzhao2 = /^[a-zA-Z0-9]{5,17}$/
	const gangao = /^[HMhm]{1}([0-9]{10}|[0-9]{8})$/
	return (userCardreg.test(idCard) || taiwanreg.test(idCard) || xianggangreg.test(idCard) || aomenreg.test(idCard) ||
		taibao.test(idCard) || huzhao1.test(idCard) || huzhao2.test(idCard) || gangao.test(idCard))
}
//获取年月日时分秒
function formatDateTime(date, fmt) {
	if (/(y+)/.test(fmt)) {
		fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
	}
	let o = {
		'M+': date.getMonth() + 1,
		'd+': date.getDate(),
		'h+': date.getHours(),
		'm+': date.getMinutes(),
		's+': date.getSeconds()
	};

	for (let k in o) {
		if (new RegExp(`(${k})`).test(fmt)) {
			let str = o[k] + '';
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str));
		}
	}
	return fmt;
}

function padLeftZero(str) {
	return ('00' + str).substr(str.length);
}
//获取年月日
function formatDate() {
	var now = new Date();
	var year = now.getFullYear();
	var month = now.getMonth() + 1;
	month = month.toString()
	month = month[1] ? month : '0' + month
	var date = now.getDate();
	date = date.toString()
	date = date[1] ? date : '0' + date
	return year + "-" + month + "-" + date;
}

//时间戳转换方法    date:时间戳数字 isTime是否显示时间 年份分隔符
function formatTimeDate(d, isTime = false, separator) {
	let dates = Number(d)
	let date = new Date(dates)
	let YY = date.getFullYear() + (separator === undefined ? "-" : separator);
	let MM = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + (separator === undefined ?
		"-" : separator);
	let DD = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate());
	let hh = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
	let mm = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
	let ss = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
	if (isTime) {
		return YY + MM + DD + " " + hh + mm + ss;
	} else {
		return YY + MM + DD
	}
}
/**
 *获取几个月前的输入日期
 *{param:DateTime} date 输入日期(YYYY-MM-DD)
 *{param:number } monthNum 月数
 */
function getPreMonthDay(date, monthNum) {
	let dateArr = date.split('-');
	let year = dateArr[0]; //获取当前日期的年份
	let month = dateArr[1]; //获取当前日期的月份
	let day = dateArr[2]; //获取当前日期的日
	let days = new Date(year, month, 0);
	days = days.getDate(); //获取当前日期中月的天数
	let year2 = year;
	let month2 = parseInt(month) - monthNum;
	if (month2 <= 0) {
		let absM = Math.abs(month2);
		year2 = parseInt(year2) - Math.ceil(absM / 12 == 0 ? 1 : parseInt(absM) / 12);
		month2 = 12 - (absM % 12);
	}
	let day2 = day;
	let days2 = new Date(year2, month2, 0);
	days2 = days2.getDate();
	if (day2 > days2) {
		day2 = days2;
	}
	if (month2 < 10) {
		month2 = '0' + month2;
	}
	let t2 = year2 + '-' + month2 + '-' + day2;
	return t2;
}
//图片旋转判断
async function compressImage(src, platform) {
	const imageInfo = await getImageInfo(src);
	const orientation = imageInfo.orientation;
	let rotate = 0;
	if (platform === 'ios') {
		rotate = 0;
	} else {
		switch (orientation) {
			case 'up': //exif:1 不旋转
				rotate = 0;
				break;
			case 'down': //exif:3 旋转180度
				rotate = 180;
				break;
			case 'right': //exif:6 旋转90度
				rotate = 90;
				break;
			case 'left': //exif:8 旋转270度
				rotate = 270;
				break;
			default:
				rotate = 0;
				break;
		}
	}
}

function getImageInfo(path) {
	return new Promise(function(resolve, reject) {
		uni.getImageInfo({
			src: path,
			success: function(image) {
				// console.log(image.width);
				// console.log(image.height);
				// console.log('orientation=' + image.orientation);
				// console.log('path=' + image.path);
				resolve(image)
			},
			fail: function(err) {
				reject(err)
			}
		});
	});
}
/**
 * 时间戳转为多久之前
 * @param String timestamp 时间戳
 * @param String | Boolean format 如果为时间格式字符串，超出一定时间范围，返回固定的时间格式；
 * 如果为布尔值false，无论什么时间，都返回多久以前的格式
 */
function hccm_timeFrom(timestamp = null, format = 'yyyy-mm-dd') {
	if (timestamp == null) timestamp = Number(new Date());
	timestamp = parseInt(timestamp);
	// 判断用户输入的时间戳是秒还是毫秒,一般前端js获取的时间戳是毫秒(13位),后端传过来的为秒(10位)
	if (timestamp.toString().length == 10) timestamp *= 1000;
	var timer = (new Date()).getTime() - timestamp;
	timer = parseInt(timer / 1000);
	// 如果小于5分钟,则返回"刚刚",其他以此类推
	let tips = '';
	switch (true) {
		case timer < 300:
			tips = '刚刚';
			break;
		case timer >= 300 && timer < 3600:
			tips = parseInt(timer / 60) + '分钟前';
			break;
		case timer >= 3600 && timer < 86400:
			tips = parseInt(timer / 3600) + '小时前';
			break;
		case timer >= 86400 && timer < 2592000:
			tips = parseInt(timer / 86400) + '天前';
			break;
		default:
			// 如果format为false，则无论什么时间戳，都显示xx之前
			if (format === false) {
				if (timer >= 2592000 && timer < 365 * 86400) {
					tips = parseInt(timer / (86400 * 30)) + '个月前';
				} else {
					tips = parseInt(timer / (86400 * 365)) + '年前';
				}
			} else {
				tips = hccm_timeFormat(timestamp, format);
			}
	}
	return tips;
}

/**
 * @param {Object} n
 * 获取n天前的日期
 */
function getDateBefore(n) {
	if (!n) {
		n = 0;
	}
	var date = new Date();

	var year = date.getFullYear();

	var month = date.getMonth() + 1;

	var day = date.getDate();

	var nowDate = year + "-" + (month < 10 ? "0" + month : month) + "-" + (day < 10 ? "0" + day : day);

	//获取30天前得日期

	var lastDate = new Date(date - 1000 * 60 * 60 * 24 * n); //最后30天可以更改，意义：是获取多少天前的时间

	var lastY = lastDate.getFullYear();

	var lastM = lastDate.getMonth() + 1;

	var lastD = lastDate.getDate();

	var LDate = lastY + "-" + (lastM < 10 ? "0" + lastM : lastM) + "-" + (lastD < 10 ? "0" + lastD : lastD); //得到30天前的时间
	return LDate;
}

//----------------------------------------------------------
//    功能：根据身份证号获得出生日期
//  参数：身份证号 psidno
//    返回值：
//    出生日期
//----------------------------------------------------------
function GetBirthday(psidno) {
	var birthdayno, birthdaytemp
	if (psidno.length == 18) {
		birthdayno = psidno.substring(6, 14)
	} else if (psidno.length == 15) {
		birthdaytemp = psidno.substring(6, 12)
		birthdayno = "19" + birthdaytemp
	} else {
		alert("错误的身份证号码，请核对！")
		return false
	}
	var birthday = birthdayno.substring(0, 4) + "-" + birthdayno.substring(4, 6) + "-" + birthdayno.substring(6, 8)
	return birthday
}

//----------------------------------------------------------
//    功能：根据身份证号获得性别
//  参数：身份证号 psidno
//    返回值：
//    性别
//----------------------------------------------------------
function Getsex(psidno) {
	var sexno, sex
	if (psidno.length == 18) {
		sexno = psidno.substring(16, 17)
	} else if (psidno.length == 15) {
		sexno = psidno.substring(14, 15)
	} else {
		alert("错误的身份证号码，请核对！")
		return false
	}
	var tempid = sexno % 2;
	if (tempid == 0) {
		sex = '2'
	} else {
		sex = '1'
	}
	return sex
}


/**
 * 上传图片
 */
const uploadImage = (archiveData) => {
	return new Promise((resolve, reject) => {
		let archive = archiveData
		uni.chooseImage({
			count: 1,
			sizeType: ['compressed'],
			success: (chooseImageRes) => {
				const tempFilePaths = chooseImageRes.tempFilePaths;
				let bizProcNam = 'jpg'
				if (tempFilePaths[0].indexOf(".jpg") != -1) {
					bizProcNam = 'jpg'
				} else if (tempFilePaths[0].indexOf(".png") != -1) {
					bizProcNam = 'png'
				}
				uni.showLoading({
					title: '正在上传',
				})
				uploadImgFunction(tempFilePaths, bizProcNam, archive).then(imgList => {
					resolve(imgList)
				})
			}
		});
	})
};

//禁用表情
function remove_utf16toEntities(str) {

	var patt = /[\ud800-\udbff][\udc00-\udfff]/g; // 检测utf16字符正则

	str = str.replace(patt, function(char) {

		var H, L, code;

		if (char.length === 2) {

			H = char.charCodeAt(0); // 取出高位

			L = char.charCodeAt(1); // 取出低位

			code = (H - 0xD800) * 0x400 + 0x10000 + L - 0xDC00; // 转换算法

			return "";

		} else {

			return char;

		}
	})
	return str
}

function uploadImgFunction(tempFilePaths, bizProcNam, archive) {
	return new Promise((resolve, reject) => {
		tempFilePaths.forEach((tempFile, index) => {
			compressImageFunc(tempFile).then(resFile => {
				uni.uploadFile({ //hccmConfig.HCCM_HOST_URL
					url: hccmConfig.HCCM_HOST_URL +
						'/js/api/ggfwCommon/common/v1/common/uploadFile', //仅为示例，非真实的接口地址
					// url: hccmConfig.HCCM_HOST_URL + '/js/api/qdyb/common/v1/ybCommon/uploadFile', //仅为示例，非真实的接口地址 老接口
					filePath: tempFile,
					name: 'fileData',
					formData: {
						objID: "55",
						objNam: "22",
						bizProcCod: "3",
						bizProcNam: bizProcNam
					},
					success: (uploadFileRes) => {
						if (uploadFileRes.statusCode == 200 && JSON.parse(
								uploadFileRes.data).code == 200) {
							uni.hideLoading();
							uni.showToast({
								title: '上传完成！',
								icon: 'none'
							})
							const FileList = JSON.parse(uploadFileRes.data)
							const imgList = {
								imgUrlThumb: FileList.data.imgUrlThumb,
								pageid: FileList.data.pageID,
								filePath: FileList.data.origiFilePath,
								archiveId: archive.archiveId,
								archiveName: archive.archiveName,
								type: '2',
								fileFormat: bizProcNam
							}
							resolve(imgList)
						} else {
							uni.hideLoading();
							uni.showToast({
								title: '上传失败！',
								icon: 'none'
							})
						}
					},
					fail() {
						uni.hideLoading();
					}
				});
			})
		})
	})

}

function compressImageFunc(tempFilePaths) {
	return new Promise((resolve, reject) => {
		uni.compressImage({
			src: tempFilePaths,
			quality: 10,
			success: res => {
				resolve(res.tempFilePath)
			},
			fail: err => {
				reject(err)
			}
		})
	})
}


module.exports = {
	GetBirthday, //根据身份证号获得出生日期
	Getsex, //根据身份证号获得性别
	hccm_timeFrom, //时间戳转为多久之前
	checkEmail, //验证邮箱格式
	checkMobile, //验证手机号格式
	checkIDCard, //校验身份证号码
	formatDate, //获取年月日
	compressImage, //图片旋转判断
	formatDateTime, //获取年月日时分秒
	getDateBefore, //获取n天前的日期
	uploadImage, //上传图片
	getPreMonthDay, //获取几个月前的输入日期
	formatTimeDate, //时间戳转换方法    date:时间戳数字 isTime是否显示时间 年份分隔符
	remove_utf16toEntities, //禁用表情
}
